<template>
  <view class="viewport">
    <!-- 地址列表 -->
    <view>
      <cc-addressSet :colors="colors" :addressList="addressList" @chooseClick="chooseClick"
        @editClick="editClick" @addressDeleted="fetchAddresses"></cc-addressSet>
      <view class="save">
        <view class="btn" :style="'background:' + colors" @tap="addAddress">添加收货地址</view>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        colors: '#fbbd08',
        addressList: []  // 地址列表数据
      };
    },
    created() {
      this.fetchAddresses();  // 页面首次加载时获取地址数据
    },
    // 页面返回时会触发onShow，确保地址数据更新
    onShow() {
      this.fetchAddresses();  // 返回页面时再次获取地址数据，确保数据刷新
    },
    methods: {
      fetchAddresses() {
        this.$service({
          url: '/addresses',
          method: 'GET'
        }).then(res => {
          if (res.code === 0) {
            this.addressList = res.data;  // 更新地址列表
          } else {
            uni.showToast({
              title: '获取地址失败',
              icon: 'none'
            });
          }
        }).catch(error => {
          console.error('请求失败:', error);
          uni.showToast({
            title: '网络错误',
            icon: 'none'
          });
        });
      },
      editClick(item) {
        // 传递地址 id，跳转到编辑页面
        uni.navigateTo({
          url: `/pagesMember/addressForm/addressForm?id=${item.id}`
        });
      },
      addAddress() {
        // 跳转到新增地址页面
        uni.navigateTo({
          url: '/pagesMember/addressForm/addressForm'
        });
      }
    }
  };
</script>

<style lang="scss">
  @import './addShowStyles.scss';
</style>
